package com.bootdo.system.controller;


import com.bootdo.system.domain.BizhongDO;
import com.bootdo.system.domain.FrontuserDO;
import com.bootdo.system.domain.JiaoyicelueDO;
import com.bootdo.system.service.*;
import com.bootdo.system.utils.MyConstant;
import com.bootdo.system.utils.R;
import com.huobi.HuobiInfoUtils;
import com.huobi.exception.SDKException;
import com.huobi.model.market.MarketTicker;
import com.sun.org.apache.bcel.internal.generic.RET;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.rtf.RTFEditorKit;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/jiaoyicelue")
public class JiaoyiCelueController extends BaseController {

    @Autowired
    private JiaoyicelueService jiaoyicelueService;
    @Autowired
    private FrontuserService frontuserService;
    @Autowired
    private BizhongService bizhongService;
    @Autowired
    private FrontlogService frontlogService;
    @Autowired
    private JiaoyijiluService jiaoyijiluService;


    @PostMapping("/maichu")
    @ResponseBody
    public R maichuone(long id) {

        return maichu(id);
    }


    @PostMapping("/maichuall")
    @ResponseBody
    public R maichuall( Long[] ids) {
        for (Long id : ids) {
            System.out.println(id);
        }

        List<R> rs = new ArrayList<>();

        for (Long id : ids) {
            R r = maichu(id);
            rs.add(r);
        }


        return R.ok("卖出结果如下：" + rs);
    }

    @GetMapping("/edit")
    public String editPage(Long id, HttpServletRequest request) {

        JiaoyicelueDO jiaoyicelueDO = jiaoyicelueService.get(id);
        request.setAttribute("jiaoyicelueDO", jiaoyicelueDO);

        return "celueedit";
    }


    @Transactional
    @PostMapping("/updateids")
    public String updateids(JiaoyicelueDO jiaoyicelueDO, HttpServletRequest request) {

        String[] bizhongids = jiaoyicelueDO.getBizhongids().split("-");

        for (String bizhongid : bizhongids) {
            jiaoyicelueDO.setBizhongid(Integer.valueOf(bizhongid));
            jiaoyicelueDO.setUserid(getUserId(request));
            jiaoyicelueService.updateByUserIdAndBizhongid2(jiaoyicelueDO);
        }


        return "redirect:/jiaoyi";
    }

    @Transactional
    @PostMapping("/update")
    public String update(JiaoyicelueDO jiaoyicelueDO) {
        System.out.println("jiaoyicelueDO=" + jiaoyicelueDO);

        jiaoyicelueService.update(jiaoyicelueDO);

        return "redirect:/jiaoyi/detail?id=" + jiaoyicelueDO.getId();
    }

    @Transactional
    @PostMapping("/editxunhuanstatus")
    @ResponseBody
    public R editxunhuanstatus(JiaoyicelueDO jiaoyicelueDO, HttpServletRequest request) {

        FrontuserDO userDO = getUserDO(request);
        if (userDO.getZichan().compareTo(BigDecimal.TEN) < 0) {
            return R.error("用户资产少于10U，修改失败");
        }
        if (userDO.getYouxiaotime() <= 0) {
            return R.error("用户未激活，请购买激活码");
        }

        jiaoyicelueDO.setUserid(getUserId(request));

        jiaoyicelueService.updateByUserIdAndBizhongid(jiaoyicelueDO);

        return R.ok("修改状态成功");
    }


    @Transactional
    @GetMapping("/editxunhuanstatus2")
    @ResponseBody
    public R editxunhuanstatus(@RequestParam("ids") Integer[] ids, @RequestParam("userid") Long userid) {

        FrontuserDO userDO = frontuserService.get(userid);
        if (userDO.getZichan().compareTo(BigDecimal.TEN) < 0) {
            return R.error("用户资产少于10U，修改失败");
        }
        if (userDO.getYouxiaotime() == null || userDO.getYouxiaotime() <= 0) {
            return R.error("用户未激活，请购买激活码");
        }

        jiaoyicelueService.updateids(ids, userid);

        return R.ok("成功，全部为策略循环");
    }


    @Transactional
    public R maichu(Long id) {
        JiaoyicelueDO celue = jiaoyicelueService.get(id);
        BizhongDO bizhongDO = bizhongService.get(celue.getBizhongid());
        if (celue.getChicangshuliang().compareTo(BigDecimal.ZERO) <= 0 || celue.getChicangjine().compareTo(BigDecimal.ZERO) <= 0) {
            return R.error("账户金额0，不可卖出 " + bizhongDO.getBizhongname());
        }
        FrontuserDO user = frontuserService.get(celue.getUserid());


        String clientOrderId = UUID.randomUUID().toString().replace("-", "");
        try {
            System.out.println("用户清场卖出=" + user.getHuobiapikey() + user.getHuobiapisecret() + clientOrderId +
                    bizhongDO.getBizhongname() + bizhongDO.getNowprice().setScale(4, RoundingMode.HALF_UP) +
                    celue.getChicangshuliang().setScale(2, RoundingMode.HALF_UP));

            MarketTicker bizhongPrice = HuobiInfoUtils.getBizhongPrice(bizhongDO.getBizhongname());

            long sellOrder = HuobiInfoUtils.createSellOrder(user.getHuobiapikey(), user.getHuobiapisecret(), clientOrderId,
                    bizhongDO.getBizhongname(), celue.getChicangshuliang());

            System.out.println("卖出" + bizhongDO.getBizhongname() + "货币 orderId= = " + sellOrder);
            //4.记录前台日志
            frontlogService.saveSellLog(user.getUserid(), 2, bizhongDO.getBizhongname(),
                    "" + sellOrder, celue.getChicangshuliang(), bizhongDO.getNowprice(), clientOrderId);
            //5.交易记录保存
            jiaoyijiluService.savejilu(user.getUserid(), "" + sellOrder, celue.getChicangshuliang(), bizhongDO.getNowprice(),
                    celue.getNowbuchangcishu(), bizhongDO, 1, MyConstant.USER_SELL_ORDER);
            //3.1如果是单次策略，运行完设置状态停止
            celue.setCeluestatus(0);
            celue.setBucangcishu(0);
            celue.setNowbuchangcishu(0);

            jiaoyicelueService.update(celue);
        } catch (SDKException e) {
            System.out.println("sdk卖出异常" + e + "   时间：" + LocalTime.now());
            return R.error(bizhongDO.getBizhongname() + "  sdk卖出异常" + e);
        } catch (Exception e) {
            System.out.println("卖出异常" + e + "   时间：" + LocalTime.now());
            return R.error(bizhongDO.getBizhongname() + "  卖出异常" + e);
        }

        return R.ok(bizhongDO.getBizhongname() + "卖出成功");
    }


}
